package com.tang.user.controller;


import com.github.pagehelper.PageInfo;
import com.tang.common.api.CommunityFeignClient;
import com.tang.common.api.CompanyJobFeignClient;
import com.tang.common.api.TransmissionFeignClient;
import com.tang.common.entity.user.Admin;
import com.tang.common.exception.RecruitExceptionEnum;
import com.tang.common.uniform.Result;
import com.tang.common.utils.JwtUtil;
import com.tang.common.utils.MD5Utils;

import com.tang.user.service.AdminService;
import com.tang.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
@Api("管理员模块")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommunityFeignClient communityFeignClient;
    @Autowired
    private TransmissionFeignClient transmissionFeignClient;
    @Autowired
    private CompanyJobFeignClient companyJobFeignClient;

    //登录
    @ApiOperation("管理员登录")
    @PostMapping("/adminLogin")
    public Result login(String adminName, String password, String captcha, HttpSession session) {
        System.out.println(session.getAttribute("captcha"));
        if (!captcha.equals(session.getAttribute("captcha"))) {
            return Result.error(RecruitExceptionEnum.CAPTCHA_ERROR);
        }
        Admin admin = adminService.find(adminName, MD5Utils.getMD5Str(password));
        if (admin == null) {
            return Result.error(RecruitExceptionEnum.USER_NOT_EXIST);
        }
        if (admin.getState() == 0) {
            return Result.error(RecruitExceptionEnum.USER_DISABLE);
        }
        String token = JwtUtil.generateToken(adminName, MD5Utils.getMD5Str(password),"admin");
        System.out.println(token);
        List list = new ArrayList();
        list.add(admin);
        list.add(token);
        return Result.success(list);
    }

    //退出登录
    @ApiOperation("管理员退出登录")
    @RequestMapping("/admin/logout")
    public Result logout(HttpSession session) {
        session.invalidate();
        return Result.success("退出成功");
    }

    //账户注销
    @ApiOperation("账户注销")
    @DeleteMapping("/admin/logoutUser")
    public Result logoutUser(String password, HttpServletRequest request, HttpSession session) {
        String token = request.getHeader("TOKEN");
        String username = JwtUtil.get(token, "username");
        String pwd = JwtUtil.get(token, "password");
        session.invalidate();
        if ("admin".equals(username)) {
            return Result.error(RecruitExceptionEnum.ADMIN_NOT_ALLOW_LOGOUT);
        }
        if (pwd.equals(MD5Utils.getMD5Str(password))) {
            int result = adminService.deleteByAdminName(username);
            if (result != 0) {
                return Result.success("注销成功");
            }
        }
        return Result.error(RecruitExceptionEnum.LOGOUT_FAILED);
    }

    //管理员列表
    @ApiOperation("管理员列表")
    @GetMapping("/admin/adminList")
    public Result adminList(String keywords,Integer currentPage,Integer pageSize) {
        PageInfo<Admin> list = adminService.list(keywords, currentPage, pageSize);
        return Result.success(list);
    }
    //添加管理员
    @ApiOperation("添加管理员")
    @PostMapping("/admin/addAdmin")
    public Result addAdmin(String adminName,String password,String realName,String tel,Integer state){
        Admin admin= new Admin();
        admin.setAdminName(adminName);
        admin.setPassword(MD5Utils.getMD5Str(password));
        admin.setRealName(realName);
        admin.setTel(tel);
        admin.setState(state);
        Admin res = adminService.selectByAdminName(adminName);
        if(res!=null){
            return Result.error(RecruitExceptionEnum.USER_HAS_EXIST);
        }
        Admin res2 = adminService.selectByTel(tel);
        if(res2!=null){
            return Result.error(RecruitExceptionEnum.TEL_HAS_USE);
        }
        int result = adminService.addAdmin(admin);
        if(result!=0){
            return Result.success("添加成功");
        }else{
            return Result.error(RecruitExceptionEnum.ADD_FAILED);
        }
    }

    //删除管理员
    @ApiOperation("删除管理员")
    @DeleteMapping("/admin/delAdmin")
    public Result delAdmin(int adminId) {
        if (adminId==1) {
            return Result.error(RecruitExceptionEnum.ADMIN_NOT_ALLOW_DELETE);
        }
        int result = adminService.deleteByAdminId(adminId);
        if (result != 0) {
            return Result.success("删除成功");
        } else {
            return Result.error(RecruitExceptionEnum.DELETE_FAILED);
        }
    }

    //启用禁用
    @ApiOperation("启用禁用")
    @PutMapping("/admin/enableDisable")
    public Result enableDisable(int adminId) {
        if (adminId == 1) {
            return Result.error(RecruitExceptionEnum.ADMIN_NOT_ALLOW_DISABLE);
        }
        int result = adminService.enableDisableByAdminId(adminId);
        if (result != 0) {
            return Result.success("操作成功");
        } else {
            return Result.error(RecruitExceptionEnum.HANDLE_FAILED);
        }
    }

    //修改密码
    @ApiOperation("修改密码")
    @PutMapping("/admin/pwdChange")
    public Result pwdChange(String adminName, String password, String newPassword) {
        Admin admin = adminService.selectByAdminName(adminName);
        if (admin == null) {
            return Result.error(RecruitExceptionEnum.USER_NOT_EXIST);
        }
        if (!admin.getPassword().equals(MD5Utils.getMD5Str(password))) {
            return Result.error(RecruitExceptionEnum.OLDPASSWORD_ERROR);
        }
        admin.setPassword(MD5Utils.getMD5Str(newPassword));
        admin.setUpdateTime(new Date());
        int result = adminService.updateAdmin(admin);
        if (result != 0) {
            return Result.success("修改成功");
        } else {
            return Result.error(RecruitExceptionEnum.UPDATE_FAILED);
        }
    }

    //重置密码
    @ApiOperation("重置密码")
    @PutMapping("/admin/resetPwd")
    public Result pwdChange(String adminName) {
        Admin admin = adminService.selectByAdminName(adminName);
        if (admin == null) {
            return Result.error(RecruitExceptionEnum.USER_NOT_EXIST);
        }
        String resetPassword="123456";
        if ("admin".equals(adminName)) {
            resetPassword = "admin";
        }
        admin.setPassword(MD5Utils.getMD5Str(resetPassword));
        admin.setUpdateTime(new Date());
        int result = adminService.updateAdmin(admin);
        if (result != 0) {
            return Result.success("重置成功");
        } else {
            return Result.error(RecruitExceptionEnum.RESET_FAILED);
        }
    }
    //获取个人信息
    @ApiOperation("获取个人信息")
    @GetMapping("/admin/personInfo")
    public Result personInfo(String adminName){
        Admin admin = adminService.selectByAdminName(adminName);
        return Result.success(admin);
    }
    //修改个人信息
    @ApiOperation("修改个人信息")
    @SneakyThrows
    @PostMapping("/admin/updatePersonInfo")
    public Result updatePersonInfo(String adminName,String sex,String birthday,String tel,String email,String address){
        Admin admin1 = adminService.selectByTel(tel);
        if(admin1!=null&&!admin1.getAdminName().equals(adminName)){
            return Result.error(RecruitExceptionEnum.TEL_HAS_USE);
        }
        Admin admin2 = adminService.selectByEmail(email);
        if(admin2!=null&&!admin2.getAdminName().equals(adminName)){
            return Result.error(RecruitExceptionEnum.EMAIL_HAS_USE);
        }
        Admin admin = adminService.selectByAdminName(adminName);
        admin.setSex(sex);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime( sdf.parse(birthday));
        calendar.add(Calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
        Date birthDay =calendar.getTime();
        admin.setBirthday(birthDay);
        admin.setTel(tel);
        admin.setEmail(email);
        admin.setAddress(address);
        int result = adminService.updateAdmin(admin);
        if(result!=0){
            return Result.success("修改成功");
        }else{
            return  Result.error(RecruitExceptionEnum.UPDATE_FAILED);
        }
    }
    @RequestMapping("/admin/dashBoard")
    public Result statistics(){
        Map<String,Integer> map = new HashMap<String,Integer>();
        Integer adminCount = adminService.getAdminCount();
        Integer userCount = userService.getUserCount(0);
        Integer companyUserCount = userService.getUserCount(1);

        Integer commentCount = null;
        try {
            commentCount = communityFeignClient.getCommentCount();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        Integer articleCount = null;
        try {
            articleCount = communityFeignClient.getArticleCount();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        Integer newsCount = null;
        try {
            newsCount = communityFeignClient.getNewsCount();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

        Integer resumeTemplateCount = null;
        try {
            resumeTemplateCount = transmissionFeignClient.getResumeTemplateCount();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        Integer liveCount = null;
        try {
            liveCount = transmissionFeignClient.getLiveCount();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        Integer videoCount = null;
        try {
            videoCount = transmissionFeignClient.getVideoCount();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

        Integer companyCount = null;
        try {
            companyCount = companyJobFeignClient.getCompanyCount();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        Integer jobCount = null;
        try {
            jobCount = companyJobFeignClient.getJobCount();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

        map.put("adminCount",adminCount);
        map.put("userCount",userCount);
        map.put("companyUserCount",companyUserCount);

        map.put("commentCount",commentCount);
        map.put("articleCount",articleCount);
        map.put("newsCount",newsCount);

        map.put("resumeTemplateCount",resumeTemplateCount);
        map.put("liveCount",liveCount);
        map.put("videoCount",videoCount);

        map.put("companyCount",companyCount);
        map.put("jobCount",jobCount);
        return Result.success(map);

    }
}
